package com.xuzhiguang.lightnat.server.core.server.proxy.util;

import com.xuzhiguang.lightnat.common.manager.ControlChannelManager;
import com.xuzhiguang.lightnat.server.core.client.NatClientService;
import com.xuzhiguang.lightnat.server.core.client.NatProxy;
import com.xuzhiguang.lightnat.server.core.server.proxy.refuse.RefuseStrategyFactory;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

@Slf4j
public class ProxyUtil {

    public static NatProxy getNatProxy(InetSocketAddress address, NatClientService natClientService) {
        return natClientService.getNatProxy(address.getHostString(), address.getPort());
    }

    public static boolean checkNatProxy(NatProxy natProxy, Channel channel) {
        if (natProxy == null) {
            log.warn("nat proxy not found. address:{}", channel.localAddress());
            RefuseStrategyFactory.getStrategy(null).refuse(channel, "nat proxy not found");
            return false;
        }
        if (ControlChannelManager.getChannel(natProxy.getClientId()) == null) {
            log.warn("nat client offline. client id:{}", natProxy.getClientId());
            RefuseStrategyFactory.getStrategy(natProxy.getProxyType()).refuse(channel, "nat client offline");
            return false;
        }
        return true;
    }
}
